﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.FileProviders;

namespace RTW.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddResponseCompression(options =>
            //{
            //    options.Providers.Add<BrotliCompressionProvider>();
            //    options.Providers.Add<GzipCompressionProvider>();
            //    options.MimeTypes =
            //        ResponseCompressionDefaults.MimeTypes.Concat(
            //            new[] { "image/svg+xml"
            //                    ,"application/javascript"
            //                    ,"application/json"
            //                    ,"application/xml"
            //                    ,"text/css"
            //                    ,"text/html"
            //                    ,"text/json"
            //                    ,"text/plain"
            //                    ,"text/xml" });
            //});
            services.AddResponseCompression();
            services.AddResponseCaching();
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddMvc().ConfigureApplicationPartManager(apm =>
            {
                // 主项目是asp.net core mvc 项目
                // 发布运行时，是用 Agile.WebPlatform.Main 主框架运行

                // 插件项目也是asp.net core mvc 项目
                // 这样需要把插件注册进来，插件的路由是有插件项目单独指定。
                // 插件core mvc项目 发布之后有两个dll文件，xxx.dll和xxx.Views.dll
                // 插件项目的命名做个约定，比如【Agile.WebPlugin.xxx】这样方便这里根据文件名注册

                // 匹配查找运行目录下的插件文件
                var targetPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
                var plugAss = Directory.EnumerateFiles(targetPath, "RTW.Web.Area.*.dll").Select(AssemblyLoadContext.Default.LoadFromAssemblyPath);
                //加载插件 Assemlby 并注册到 MvcBuilder 中
                foreach (var item in plugAss)
                {
                    foreach (var part in new DefaultApplicationPartFactory().GetApplicationParts(item))
                    {
                        apm.ApplicationParts.Add(part);
                    }

                    foreach (var part in new CompiledRazorAssemblyApplicationPartFactory().GetApplicationParts(item))
                    {
                        apm.ApplicationParts.Add(part);
                    }
                }
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseResponseCompression();
            app.UseResponseCaching();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(env.WebRootPath, @"layuiadmin")),
                RequestPath = new PathString("/layuiadmin"),
                ContentTypeProvider = new FileExtensionContentTypeProvider(
                new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
                {
                    { ".html","text/html"},
                    { ".js", "application/javascript" },
                    { ".css", "text/css" },
                    { ".png", "image/png" },
                    { ".jpg", "image/jpeg" },
                    { ".gif","image/gif"},
                    { ".ico", "image/x-icon" },
                    { ".json", "application/json" },
                    { ".woff2", "application/x-font-woff" },
                    { ".woff", "application/x-font-woff" },
                    { ".ttf", "application/octet-stream" },
                    { ".otf", "application/octet-stream" },
                    { ".xls", "application/octet-stream" },
                    { ".eot","application/vnd.ms-fontobject" },
                    { ".svg","image/svg+xml"}
            })
            }

                );
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                //主页
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                //模块管理
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            });
        }


    }
}
